<template>
  <div class="manuscriptPreview">
    <HomeHeader :isMine="true"></HomeHeader>
    <div class="manuscriptPreview-mian">
      <div class="left">
        <div class="title">
          <div class="title-left">
            <div class="title-text">稿件预览</div>
            <p>您可以在此预览将要交付的稿件.</p>
          </div>
          <div class="title-right">
            <div v-if="numberReject.status == 5" class="edit-sug" @click="handleOpenEditSug">
            </div>
            <div v-if="numberReject.status == 5" class="confirm-recieve" @click="handleOpenConfirmRecieve"></div>
            <div v-else class="confirm-recieve-forbidden"></div>
          </div>
        </div>
        <div class="left-content mt-12 scrollbar-class" @copy="handleCopy" v-loading="contentLoading">
          <div class="left-content-title">
            {{ currentPage.pageName }}
          </div>
          <!-- <p class="mt-24 scrollbar-class" style="font-family:  'Microsoft YaHei'; color: #000000;" v-html="curContent"> -->
          
          <p class="mt-24 scrollbar-class" style="font-family:  'Microsoft YaHei'; color: #000000;">
            <iframe :srcdoc="curContent" width="100%" height="100%" frameborder="0" allowfullscreen></iframe>

          </p>
        </div>
      </div>
      <div class="right">
        <div class="title">
          <div class="title-left">
            <div class="title-text">稿件列表</div>
            <p>此处列出当前任务中的所有稿件.</p>
          </div>
        </div>
        <div class="left-content scrollbar-class mt-12">
          <div class="tab-list">
            <div
              class="tab-item"
              :class="{ 'active-item ': item.name === currentVersion.name }"
              v-for="(item, index) in versionList"
              :key="index"
              @click="handleChangeTab(item)"
            >
              {{ item.name }}
            </div>
          </div>
          <div class="tab-list-content mt-16">
            <div
              class="tab-content-item"
              v-for="(item, index) in currentVersion.pageList"
              :key="index"
              :class="{
                'active-item-content': item.id === currentPage.id,
              }"
              @click="handleOpenpage(item)"
            >
              <div class="tab-item-name">
                <img
                  class="tab-item-icon"
                  src="@/assets/image/mine/icon／manuscript／black@2x.png"
                  alt=""
                />
                <span class="tab-item-text">{{ item.pageName }}</span>
              </div>
              <span class="new-tag" v-if="item.isNew">新</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <diaolog
    ref="recieveRef"
    confirmText="确认接收"
    @confirm="handleConfirmRecieve"
  >
    <template #title>确认接受稿件</template>
    <span
      >确认接受稿件意味着 (自确认接受时刻30天内)您将能够下载稿件到您的设备中,
      此任务也将被标记为已完成.</span
    >
  </diaolog>
  <el-dialog
    class="edit-sug-diaolog-container"
    :show-close="false"
    :close-on-click-modal="false"
    center
    align-center
    v-model="dialogVisible"
  >
    <template #header>
      <div class="diaolog-header">
        <div>修改意见</div>
        <p class="header-text">写下您的想法...</p>
      </div>
    </template>
    <div class="confirm-diaolog-content">
      <ClientOnly>
        <editorComponent ref="editRef"></editorComponent>
      </ClientOnly>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="() => {dialogVisible = false; editRef.setEditor('')}">取消</el-button>
        <el-button type="primary" @click="handleSubmitEditSug">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  <weekDiaolog buttonText="我知道了" ref="weekDiaologRef" @confirm="confirmWeekDiaolog">
    <template #title>
      <div class="mine-week-diaolog-container-pay-box">
        <div class="title">{{ weekDiaologInfo.title }}</div>
        <p>{{ weekDiaologInfo.tips }}</p>
        <div class="slider"></div>
      </div>
    </template>
    <p v-html="weekDiaologInfo.content"></p>
  </weekDiaolog>
</template>

<script setup>
import HomeHeader from "@/components/homePage/header/index.vue";
import diaolog from "@/components/mine/diaolog.vue";
import EventBus from "@/utils/eventBus.js";
import editorComponent from "@/components/mine/editorComponent.vue";
import { useRoute, useRouter } from "vue-router";
import { updateTask } from "@/utils/api/customerService/index";
import { queryTaskList } from "@/utils/api/customerService/index";
import weekDiaolog from "@/components/mine/weekDiaolog.vue";

import { useStore } from "@/store/index";
const store = useStore();
const weekDiaologRef = ref(null);
const weekDiaologInfo = ref({
  title: "提交成功",
  tips: "您还有",
  content:
    "已收到您的修改意见. <br/>>编辑们根据您的描述完成修改后, 会通过平台给您发送新版稿件.",
});
const numberReject = ref({
  all: 0,
  now: 0,
  status: ''
});
const route = useRoute();
const router = useRouter();
const taskId = route.query.taskId;
let demandId = ''
const dialogVisible = ref(false);
const recieveRef = ref(null);
const versionList = ref([]);
const currentVersion = ref({});
const currentPage = ref({});
const editRef = ref(null);
const confirmWeekDiaolog = () => {
  returnToMine()
  weekDiaologRef.value.settingVisible(false);
};
const handleSubmitEditSug = () => {
  let content = editRef.value.getEditor();
  if (content > 2000) {
    EventBus.emit("openToastBox", [
      "修改意见不能多于2000字！有更多需求可联系客服。",
    ]);
    return;
  }
  updateTask({
      switch: 2,
      keyword_id: taskId,
      reject: content
    }).then(res => {
      let resData = JSON.parse(res.data.value || '{}');
      if (resData.code === 200) {
  // EventBus.emit("openToastBox", ["修改意见已成功提交"]);
  weekDiaologRef.value.settingVisible();
  weekDiaologInfo.value = {
    title: "提交成功",
    tips: `您还有${
      numberReject.value.now - 1 >= 0 ? numberReject.value.now - 1 : 0
    }次修改次数.`,
    content:
      "已收到您的修改意见. <br/>编辑们根据您的描述完成修改后, 会通过平台给您发送新版稿件.",
  };
  dialogVisible.value = false;
    }else{
      EventBus.emit("openToastBox", [resData.message || '提交失败！']);
    }
  })
};
const handleChangeTab = (item) => {
  currentVersion.value = item;
  handleOpenpage(item.pageList[0] || {});
};
const handleCopy = (e) => {
  e.preventDefault(); // 阻止复制事件的默认行为
};
const handleOpenConfirmRecieve = () => {
  recieveRef.value.settingVisible();
};
const handleConfirmRecieve = () => {
  updateTask({
    switch: 3,
    keyword_id: taskId,
  }).then((res) => {
    let resData = JSON.parse(res.data.value || "{}");
    if (resData.code === 200) {
      recieveRef.value.settingVisible(false);
      EventBus.emit("openToastBox", ["稿件已成功接收"]);
      setTimeout(() => {
        returnToMine()
      }, 300);
    } else {
      EventBus.emit("openToastBox", [resData.message || "提交失败！"]);
    }
  });
};
const returnToMine = () => {
  router.push({ name: 'mine', state: { demandId: demandId,
    taskId: taskId } })
}
const handleOpenEditSug = () => {
  if (numberReject.value.now <= 0) {
    weekDiaologRef.value.settingVisible();
    weekDiaologInfo.value = {
      title: "您的修改次数已用完",
      tips: `您还有0次修改次数.`,
      content:
        `平台将会为您的每个任务分配${numberReject.value.all}次修改机会. 若您仍需修改文章, 请联系人工客服获取帮助.`,
    };
  } else {
    dialogVisible.value = true;
  }
};
const queryTaskDetail = () => {
  queryTaskList({
    keyword_id: taskId,
  }).then((res) => {
    let resData = JSON.parse(res.data.value || "{}");
    let curTask = resData.result?.data?.[0] || {};
    if (resData.code === 200) {
      numberReject.value.all = curTask?.DemandList?.reject_num_ok;
      numberReject.value.now = curTask?.reject_num_now;
      numberReject.value.status = curTask?.status;
      demandId = curTask?.DemandList?.id;
    }
  });
};
// 获取稿件预览
const initPreview = () => {
  updateTask({
      switch: 5,
      keyword_id: taskId,
    }).then(res => {
      let resData = JSON.parse(res.data.value || '{}');
        versionList.value = (resData.result || []).map((dd, indexD) => {
          let text_url = JSON.parse(dd.text_url || '{}')
          return {
            name: `VER.${(resData.result || []).length - indexD}`,
            pageList: text_url.map((cc, inde) => ({
              pageName: cc.name,
              content: cc.url,
              id: inde
            }))
          }
        });
        handleChangeTab(versionList.value[0])
  })
}
const contentLoading = ref(false);
const curContent = ref('');
const handleOpenpage = async(item) => {
  contentLoading.value = true;
  if (!item.content) {
    EventBus.emit("openToastBox", ['稿件正在生成中，请稍后再试！']);
    return;
  }
  //请求对应的html内容
  try {
      const response = await fetch(item.content, {method: 'GET'}); // 替换为你的请求地址
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      curContent.value = await response.text(); // 获取返回的文本内容
      contentLoading.value = false;
    } catch (error) {
      EventBus.emit("openToastBox", ['Fetch 请求出错！']);
      throw error; // 抛出错误，可以在组件中处理错误逻辑
    }
  currentPage.value = item
}
onMounted(() => {
  if (process.client) {
    nextTick(() => {
      queryTaskDetail();
      initPreview()
    });
  }
});
</script>

<style lang="scss" scoped>
.manuscriptPreview {
  overflow: hidden;
  padding-bottom: 20px;
  background: #F3F3F5;
  height: 100%;
  box-sizing: border-box;
  .manuscriptPreview-mian {
    width: $aiseoHomeWidth;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    padding-top: 76px;
    height: 100%;
    box-sizing: border-box;
    .left {
      width: 800px;
      .title {
        display: flex;
        justify-content: space-between;
        .title-left {
          .title-text {
            font-weight: bold;
            font-size: 16px;
            color: #2e2f33;
          }
          p {
            font-weight: 400;
            font-size: 12px;
            color: #7b7c80;
          }
        }
        .title-right {
          display: flex;
          justify-content: space-between;
          .edit-sug {
            width: 144px;
            height: 52px;
            background: url("@/assets/image/mine/button／modifyManuscript／normal@2x.png")
              no-repeat;
            background-size: cover;
            cursor: pointer;
            &:hover {
              background: url("@/assets/image/mine/button／modifyManuscript／hover@2x.png")
                no-repeat;
              background-size: cover;
            }
          }
          .confirm-recieve {
            width: 191px;
            height: 52px;
            background: url("@/assets/image/mine/button／confirmAccept／normal@2x.png")
              no-repeat;
            background-size: cover;
            cursor: pointer;
            &:hover {
              background: url("@/assets/image/mine/button／confirmAccept／hover@2x.png")
                no-repeat;
              background-size: cover;
            }
          }
          .confirm-recieve-forbidden{
            width: 191px;
            height: 52px;
            background: url("@/assets/image/mine/button／confirmAccept／forbid@2x.png")
              no-repeat;
            background-size: cover;
          }
          img {
            width: 100%;
            height: 100%;
          }
        }
      }
      .left-content {
        background: #FFFFFF;
        border-radius: 8px;
        padding: 24px;
        box-sizing: border-box;
        -webkit-user-select: none;
        -moz-user-select: none;
        user-select: none;
        width: 100%;
        min-height: 700px;
        height: 700px;
        overflow: auto;
        height: calc(100% - 60px);
        .left-content-title {
          font-weight: bold;
          font-size: 14px;
          color: #7b7c80;
        }
        > p {
          font-weight: 400;
          font-size: 14px;
          color: #7b7c80;
          line-height: 28px;
          height: calc(100% - 45px);
          .preview-img{
            width: 100%;
            object-fit: contain;
          }
        }
      }
    }
    .right {
      width: 380px;
      .title-left {
        height: 52px;
        .title-text {
          font-weight: bold;
          font-size: 16px;
          color: #2e2f33;
        }
        p {
          font-weight: 400;
          font-size: 12px;
          color: #7b7c80;
        }
      }
      .left-content {
        background: #FFFFFF;
        border-radius: 8px;
        padding: 24px;
        box-sizing: border-box;
        width: 100%;
        height: 700px;
        overflow: auto;
        height: calc(100% - 60px);
        .tab-list {
          display: flex;
          font-family: Komu A, Komu A;
          font-weight: 400;
          font-size: 16px;
          color: #7b7c80;
          .tab-item {
            cursor: pointer;
            & + .tab-item {
              margin-left: 16px;
            }
          }
          .active-item {
            color: #2e2f33;
          }
        }
        .tab-list-content {
          .tab-content-item {
            padding: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
            & + .tab-content-item {
              margin-top: 8px;
            }
            .tab-item-name {
              display: flex;
              align-items: center;
            }
            .tab-item-icon {
              width: 16px;
              height: 16px;
            }
            .tab-item-text {
              margin-left: 8px;
              font-weight: bold;
              font-size: 14px;
              color: #2e2f33;
              max-width: 273px;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
            }
            .new-tag {
              font-family: HelloFont WenYiHei, HelloFont WenYiHei;
              font-weight: 400;
              font-size: 8px;
              color: #e62e3d;
              text-shadow: 1px 1px 2px rgba(179, 18, 21, 0.12);
            }
            &:hover {
              background: rgba(217, 217, 219, 0.5);
              border-radius: 4px;
            }
          }
          .active-item-content {
            background: #d9d9db;
            border-radius: 4px;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
.edit-sug-diaolog-container {
  padding: 20px !important;
  font-weight: 400 !important;
  font-size: 14px !important;
  color: #606166 !important;
  line-height: 24px !important;
  text-align: center !important;
  box-sizing: border-box !important;
  background: #fff !important;
  box-shadow: 3px 6px 12px 1px rgba(8, 52, 128, 0.08) !important;
  border-radius: 12px !important;
  min-width: 672px !important;
  width: auto !important;
  max-width: 1200px !important;
  .el-dialog__header {
    font-weight: bold;
    font-size: 16px;
    color: #2e2f33;
    text-align: left;
    .header-text {
      font-weight: 400;
      font-size: 12px;
      color: #7b7c80;
    }
  }
  .confirm-diaolog-content {
    width: 100%;
    background: #FAFAFA;
    border-radius: 8px;
    padding: 12px;
    font-weight: 400;
    font-size: 14px;
    color: #606166;
    line-height: 24px;
    box-sizing: border-box;
    min-height: 120px;
  }
  .el-button {
    border: none;
    background: none;
    font-weight: bold;
    font-size: 14px;
    color: #2e2f33;
  }
  .el-button--primary {
    padding: 12px 24px;
    box-shadow: 1px 2px 4px 1px rgba(219, 134, 60, 0.24);
    border-radius: 8px 8px 8px 8px;
    border: 2px solid #e68837;
    color: #e68837;
  }
}
.mine-week-diaolog-container-pay-box{
  text-align: left !important;
  .title{
    font-weight: bold !important;
    font-size: 16px !important;
    color: #2E2F33 !important;
  }
  p{
    font-weight: 400 !important;
    font-size: 12px !important;
    color: #ABAEB3 !important;
  }
  .slider{
    width: 100% !important;
    height: 1px !important;
    background: #C6C7CC !important;
    margin-top: 20px !important;
  }
}
</style>
